<?php
namespace app\common;

use think\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

// 七牛云
class Qiniu {

    /**
     * 文件上传类
     * @param [file] $file     【必填】[文件内容]
     * @param string $filename 【非必填】[文件名，传值表示删除文件]
     * @param string $prefix   【非必填】[文件前缀]
     * @return array [ "state"=>1,//1成功0失败 "msg"=>"上传完成","data"=>'图片路径' ];
     */
	public function upload($file, $filename='', $prefix='')
	{
		if( empty($file) ) return ["state"=>0,"msg"=>"文件不存在"];
		$filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key = $prefix. substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        // require_once APP_PATH . '/../vendor/Qiniu/autoload.php';
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = Config::get('config.accessKey');
        $secretKey = Config::get('config.secretKey');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = Config::get('config.bucket');
        $token = $auth->uploadToken($bucket);

        // 删除文件
        if( $filename ) {
            $config = new \Qiniu\Config();
            $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
            $err = $bucketManager->delete($bucket, $filename);
            // if ($err) return ["state"=>0,"msg"=>"删除失败","data"=>$err];
        }

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return ["state"=>0,"msg"=>$err,"data"=>""];
        } else {
            //返回图片的完整URL
            return [ "state"=>1,"msg"=>"上传完成","data"=>$ret['key'] ];
        }
	}

    /**
     * [deleteFile description]
     * @param  [type] $filename [description]
     * @return [type]           [description]
     */
	public function deleteFile($filename)
	{
		if( empty($filename) ) return ["state"=>0,"msg"=>"文件名不存在"];
		$accessKey = Config::get('config.accessKey');
        $secretKey = Config::get('config.secretKey');
		$auth = new Auth($accessKey, $secretKey);
		$bucket = Config::get('config.bucket');
		$config = new \Qiniu\Config();
		$bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
		list($ret, $err) = $bucketManager->delete($bucket, $filename);
		if ($err !== null ) {
            // return ["state"=>0,"msg"=>$err,"data"=>""];
            return ["state"=>1,"msg"=>$err,"data"=>""];
        } else {
            //返回图片的完整URL
            return ["state"=>1,"msg"=>"删除完成","data"=>$ret ];
        }
	}

}






